import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import QueueAnim from 'rc-queue-anim';
import OverPack from 'rc-scroll-anim/lib/ScrollOverPack';
import classNames from 'classnames';
import { Checkbox, Alert, message } from 'antd';
import { Login } from 'ant-design-pro';
import Geetest from '@/components/Geetest';
import styles from './style.less';

const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;

@connect(({ login, loading }) => ({
  login,
  submitting: loading.effects['login/login'],
}))
class LoginPage extends Component {
  state = {
    type: '0',
    autoLogin: true,
    captchaObj: null,
    geeTestErrno: 0,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'login/getGeeTest' }, ({ errno }) => errno && message.error('初始化极验验证失败！'));
  }

  onTabChange = type => {
    this.setState(state => ({ ...state, type }));
  };

  handlerGeetest = captchaObj => {
    this.setState(state => ({ ...state, captchaObj }));
  }

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      this.loginForm.validateFields(['mobile'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          dispatch({
              type: 'login/getCaptcha',
              payload: values.mobile,
            })
            .then(resolve)
            .catch(reject);
        }
      });
    });

  handleSubmit = (err, values) => {
    const { type, captchaObj = {} } = this.state;

    if (captchaObj.getValidate && !captchaObj.getValidate() && type === '0') {
      this.setState(state => ({ ...state, geeTestErrno: -1 }));
      return;
    }
    this.setState(state => ({ ...state, geeTestErrno: 0 }));

    if (!err) {
      const { dispatch } = this.props;
      dispatch({
        type: 'login/login',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  changeAutoLogin = e => {
    this.setState(state => ({
      ...state,
      autoLogin: e.target.checked,
    }));
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} className="shake animated" message={content} type="error" showIcon />
  );

  render() {
    const { login, submitting } = this.props;
    const { type, autoLogin, geeTestErrno } = this.state;
    return (
      <div className={classNames(styles.main, 'rubberBand animated')}>
        <Login
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={form => { this.loginForm = form }}
        >
          <Tab key="0" tab={formatMessage({ id: 'user-login.login.tab-login-credentials' })}>
            {login.get('errno') === -1 &&
              login.get('type') === '0' &&
              !submitting &&
              this.renderMessage(formatMessage({ id: 'user-login.login.message-invalid-credentials' }))}
            {geeTestErrno === -1 && type === '0' && !submitting && this.renderMessage('滑块儿验证失败！')}
            <UserName
              name="userName"
              placeholder={`${formatMessage({ id: 'user-login.login.userName' })}`}
              rules={[
                { required: true, message: formatMessage({ id: 'user-login.userName.required' }) },
              ]}
            />
            <Password
              name="password"
              placeholder={`${formatMessage({ id: 'user-login.login.password' })}`}
              rules={[
                { required: true, message: formatMessage({ id: 'user-login.password.required' }) },
              ]}
              onPressEnter={() => this.loginForm.validateFields(this.handleSubmit)}
            />
            <Geetest {...login.get('geeTest')} onGeetest={this.handlerGeetest} />
          </Tab>
          <Tab key="1" tab={formatMessage({ id: 'user-login.login.tab-login-mobile' })}>
            {login.get('errno') === -1 &&
              login.get('type') === '1' &&
              !submitting &&
              this.renderMessage(
                formatMessage({ id: 'user-login.login.message-invalid-verification-code' })
              )}
            <OverPack playScale={0.1}>
              <QueueAnim
                type={['bottom', 'top']}
                className={styles.top}
                leaveReverse
                key="mobile"
              >
                <Mobile
                  key="mobile"
                  name="mobile"
                  placeholder={formatMessage({ id: 'user-login.phone-number.placeholder' })}
                  rules={[
                    { required: true, message: formatMessage({ id: 'user-login.phone-number.required' }) },
                    { pattern: /^1\d{10}$/, message: formatMessage({ id: 'user-login.phone-number.wrong-format' }) },
                  ]}
                />
                <Captcha
                  key="captcha"
                  name="captcha"
                  placeholder={formatMessage({ id: 'user-login.verification-code.placeholder' })}
                  countDown={120}
                  onGetCaptcha={this.onGetCaptcha}
                  rules={[
                    { required: true, message: formatMessage({ id: 'user-login.verification-code.required' })},
                  ]}
                />
              </QueueAnim>
            </OverPack>
          </Tab>
          <div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="user-login.login.remember-me" />
            </Checkbox>
          </div>
          <Submit loading={submitting}>
            <FormattedMessage id="user-login.login.login" />
          </Submit>
        </Login>
      </div>
    );
  }
}

export default LoginPage;